//
//  SWEventPhotoViewController.swift
//  ChildStory
//
//  Created by linhan on 2016/11/16.
//  Copyright © 2016年 Aiya. All rights reserved.
//

import Foundation
import UIKit



class SWEventPhotosViewController: SWBaseViewController,UICollectionViewDataSource,UICollectionViewDelegate,CollectionViewCellDelegate,SWImagePickerControllerDelegate
{
    var eventID:String = ""
    weak var event:SWKidEvent?
    
    //private var _favoriteRecords:[SWAssetRecord] = []
    
    private var _photos:[SWALPhoto] = []
    
    private var _collectionView:UICollectionView?
    
    private var _addItem:SWALPhoto = SWALPhoto(thumbnail: UIImage(named:"editor_icon_camera"))
    
    deinit
    {
        print("DEINIT SWEventPhotosViewController")
    }
    
    override var prefersNavigationBarHidden: Bool{
        return false
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setup()
    }
    
    private func setup()
    {
        var numOfHorizontal:Int = 4
        if SWDevice.size > .iPhone47inch{
            numOfHorizontal = 5
        }
        
        let Grid:CGFloat = 4
        let cellWidth:CGFloat = (self.view.width - (CGFloat(numOfHorizontal + 1) * Grid)) / CGFloat(numOfHorizontal)
        let layout:UICollectionViewFlowLayout = UICollectionViewFlowLayout()
        layout.itemSize = CGSizeMake(cellWidth, cellWidth)
        //横向最小间隔
        layout.minimumInteritemSpacing = Grid
        //纵向最小间隔
        layout.minimumLineSpacing = Grid
        layout.sectionInset = UIEdgeInsetsMake(Grid, Grid, Grid, Grid)
        
        _collectionView = UICollectionView(frame: view.bounds, collectionViewLayout: layout)
        _collectionView?.backgroundColor = UIColor.white
        _collectionView?.register(SWEventPhotoCollectionCell.self, forCellWithReuseIdentifier: "SWEventPhotoCollectionCell")
        _collectionView?.dataSource = self
        _collectionView?.delegate = self
        view.addSubview(_collectionView!)
        
        
        DispatchQueue.global(priority: .default).async {
            self.loadPhoto()
        }
    }
    
    private func loadPhoto()
    {
        if eventID == ""
        {
            return
        }
        
        _photos = [_addItem]
        
        let assets = SWAssetsManager.sharedManager().assets.filter({($0.eventID ?? "") == eventID})
        let ids:[String] = assets.filter({$0.valid}).map({$0.localID})
        _photos += SWAssetsLibraryHelper.shared().fetchAssets(localIdentifiers: ids)
        
        
        
        DispatchQueue.main.async {
            self._collectionView?.reloadData()
            self._collectionView?.alpha = 0
            UIView.animate(withDuration:0.2, animations: {
                self._collectionView?.alpha = 1
            })
        }
    }
    
    //MARK ============================================================================================
    //==============================              Delegate              ===============================
    //=================================================================================================
    
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
    {
        return _photos.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
    {
        let cell:SWEventPhotoCollectionCell = collectionView.dequeueReusableCell(withReuseIdentifier: "SWEventPhotoCollectionCell", for: indexPath) as! SWEventPhotoCollectionCell
        cell.delegate = self
        let index:Int = indexPath.row
        if let photo = _photos.valueAt(index)
        {
            cell.photo = photo
            photo.fetchThumbnail()
        }
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath)
    {
        if indexPath.row == 0
        {
            let pickerController = SWImagePickerController()
            pickerController.delegate = self
            pickerController.allowsMultipleSelection = true
            pickerController.maxCount = 3
            let navigation = SWBaseNavigationController(rootViewController: pickerController)
            present(navigation, animated: true, completion:nil)
        }
        else
        {
            /**
            if let photo = _photos.valueAt(indexPath.row)
            {
                SWAssetsLibraryHelper.shared().fetchOriginImage(photos: [photo], completeCallback: {[weak self] results in
                    if let image = results.valueAt(0)?.image
                    {
                        self?._photo = image
                        self?.showPhotoViewer(index: max(indexPath.row - 1, 0))
                    }
                }, options: nil)
            }//end photo
            **/
            let localIdentifiers:[String] = _photos.flatMap({$0.localIdentifier}).filter({$0 != ""})
            let viewController = SWPhotosDetailViewController(localIdentifiers: localIdentifiers)
            viewController.index = indexPath.row - 1
            navigationController?.pushViewController(viewController, animated: true)
        }//end else
    }
    
    func collectionViewCell(_ cell:UICollectionViewCell, click action:String, argument aArgument:[AnyHashable:Any]?)
    {
        if action == CallbackAction.LongPress
        {
            
        }
    }
    
    func imagePickerController(_ picker: SWImagePickerController, didFinishPickingMediaWithPhotos photos: [SWALPhoto])
    {
        let aPhotos = photos.reversed()
        for photo in aPhotos
        {
            let record:SWAssetRecord = SWAssetRecord()
            record.localID = photo.localIdentifier
            _photos.insertSafely(photo, atIndex: 1)
        }
        
        //添加全局记录
        let aEvent:SWKidEvent? = event ?? SWKidEvent(eventID:eventID)
        let localIdentifiers:[String] = photos.flatMap({$0.localIdentifier}).filter({$0 != ""})
        SWAssetsManager.sharedManager().addAssets(localIDs: localIdentifiers, event: aEvent)
        
        _collectionView?.reloadData()
        
        picker.close()
    }
    
    func imagePickerControllerDidCancel(_ picker: SWImagePickerController)
    {
        picker.close()
    }
    
    
    
    
}
